package com.mayn.jst.erp.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.mayn.jst.login.TaobaoLoginAction;
import com.mayn.util.DateUtil;
import com.mayn.util.SendCloudMailUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;;

/**
 * 淘宝客抓取类
 * @author 梁志渊
 * @version 
 * 版本号：【100-000-000】<br/>
 * 创建日期：:2017年7月4日 <br/>
 * 历史修订：<br/>
 */
public class ShopUnionFeeAction {

	private static final Logger LOG = LoggerFactory.getLogger(ShopUnionFeeAction.class);
	/**
	 * @author 梁志渊
	 * 淘宝客抓取
	 * @param ShopId
	 * @param date
	 */
	public static  void TestShopUnionFee(Date currTime) {
		
		//初始化数据库
//		JfinalInit.InitDb(false, null);	
		
		int shopId = 5;//设置店铺ID
		String id = null;
		//初始化map
		List<Map<String, Object>> ListMap = null;
		String date = DateUtil.dateFmtToString(currTime,"yyyy-MM-dd");
//		String date = "2017-09-02";
		//开始时间
		JSONArray jsonArray = null;
		
		try {
			
		//cookie
		String cookie = TaobaoLoginAction.checkAndGetAlimamaLoginCookie(shopId);
		//获取的jsonArray 数据集合
		jsonArray = TaobaoLoginAction.getMyunionTkTrans(cookie,date,date);
		 //jsonArray 传 map中去
		 ListMap =  InsertToMap(jsonArray);
					
		 //插入数据
		 		for (int j = 0; j < ListMap.size(); j++) {
		 			Map<String, Object> map =new HashMap<String,Object>();
		 			map = ListMap.get(j);
		 			//打印数据
		 			id = ListMap.get(j).get("tbTradeId").toString();
		 			LOG.info("tbTradeId--->"+id);
		 			if( checkSufData(shopId, date,id) == true){
		 				LOG.error("数据已存在,跳过采集");
		 				continue;
		 			}else{
		 			//判断数据完整性
		 				if(savedata(map,shopId,date) != true) {//save操作 date为抓取时间
		 					LOG.info("date:"+date+"插入失败！");
						return;
					}else {
						LOG.info("date:"+date+"插入成功！");
					}
		 		}
		 	}
		} catch (Exception e) {
			e.printStackTrace();
			String mailText = "淘宝客数据抓取失败"+"\r\n"+Thread.currentThread().getStackTrace()[1].getMethodName() + " Exception,Msg=" + e.getMessage();
		    SendCloudMailUtil.sendMailCode(mailText,"service@mayn.com.cn");
			}
		}
	
	/**
	 * 插入map操作
	 * @author lzy
	 * @param jsonArray 传入的jsonArray参数
	 * @param map 要插入的map
	 * @return 
	 * @return map
	 */
	public static List<Map<String, Object>>  InsertToMap(JSONArray jsonArray){
		//创建传递map
		List<Map<String, Object>>  listmap =  new ArrayList<Map<String, Object>>();
		//循环插入数据
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<String, Object> map = new HashMap<String,Object>();
			//取出一行数据
			JSONObject jsonObject = jsonArray.getJSONObject(i);
//			LOG.info("一行数据：campaignId->"+jsonObject.get("campaignId").toString());
			//JSONObject 转map
			Iterator<?> it = jsonObject.keys();
			//取出每条数据的键值对
			while (it.hasNext()) {
				String key = String.valueOf(it.next());
				Object value = jsonObject.get(key);
				map.put(key, value);
			}
			listmap.add(i, map);
		}
			return listmap ;
	}

	/**
	 *  检查淘宝客数据库是否有数据并检查日期
	 * @author 梁志渊
	 * @return false:无 true:有
	 */
	public static  Boolean checkSufData(int shopId,String date,String id) {
		//查询数据库 条数
		String sql = "select COUNT(*) from shop_union_fee suf  where   suf.SUF_DEL=0  and suf.SUF_DATE = ? and suf.SUF_TB_TRADEID = ? ";
		int count =  0;//数据库中数据条数
		try {
			count=  Db.use("erp").queryLong(sql,date,id).intValue();
			if( count >= 1){
				return true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 插入淘宝客数据
	 * @param map
	 * @param shopId 店铺id
	 * @param sufdate 日期
	 * @author 梁志渊
	 * @return false:插入失败 true:插入成功
	 */
	public static  Boolean savedata( Map<String, Object>  map,int ShopId,String sufdate) {
		
		try {
			int ret = -1;//插入标志
			int campaignId = 0;//计划ID'
			Date sufDate = DateUtil.stringFmtToDate(sufdate,"yyyy-MM-dd");//suf抓取时间
			int shopId = ShopId;//店铺ID
			String campaignName = "";//计划名称
			Double commissionRate = 0.0;//佣金率
			String tbTradeParentId = "";//淘宝交易父单号
			String tbTradeId = "";			//淘宝交易单号
			String tbAuctionTitle ="";		//淘宝拍卖商品名称
			String earningTime = "";		//收益时间
			Double tkCommissionFee = 0.0;//淘宝客佣金
			String nickname = "";				//客户昵称
			Double tkCommissionRate = 0.0;//淘宝客佣金率
			Double tbAuctionPrice = 0.0;	 //淘宝拍卖价格
			int tbAuctionNum =0;				//淘宝拍卖数量
			int tkPubId = 0;						//
			Double tbFinishTotalPrice = 0.0;//淘宝结算总金额
			Date tbTradeCreateTime =   null;//淘宝交易创建时间
			Date tbTradeFinishTime = null;//淘宝交易结束时间
			String fmtCommissionRate ="";//FMT佣金率
			String fmtCommissionFee = "";//FMT佣金
			String fmtAuctionPrice = "";		//FMT拍卖价格
			String fmtTbFinishTotalPrice = "";//FMT淘宝结算总金额
			
			Date sufCreateDatetime =DateUtil.dateToTimestamp(new Date()  ) ;//创建时间
			int 	sufCreateBy = 1;//创建人
			Date sufModifyDatetime = DateUtil.dateToTimestamp(new Date()) ;//修改时间
			int    sufModifyBy	= 1;//修改人
			int    sufDel = 0;		 //未删除
			

			 campaignId = (int) map.get("campaignId");
			
			 campaignName = map.get("campaignName").toString();
			 commissionRate = (Double) map.get("commissionRate");
			 tbTradeParentId = map.get("tbTradeParentId").toString();
			 tbTradeId = map.get("tbTradeId").toString();
			 tbAuctionTitle = map.get("tbAuctionTitle").toString();
			 earningTime = map.get("earningTime").toString();
			 tkCommissionFee = (Double) map.get("tkCommissionFee");
			 nickname = map.get("nickname").toString().replace("'", "''");
			 tkCommissionRate = (Double) map.get("tkCommissionRate");
			 tbAuctionPrice = (Double) map.get("tbAuctionPrice");
			 tbAuctionNum = (int) map.get("tbAuctionNum");
			 tkPubId = (int) map.get("tkPubId");
			 tbFinishTotalPrice = (Double) map.get("tbFinishTotalPrice");
			 tbTradeCreateTime =  DateUtil.stringFmtToDate(map.get("tbTradeCreateTime").toString(),"yyyy-MM-dd");
			 tbTradeFinishTime = DateUtil.stringFmtToDate(map.get("tbTradeFinishTime").toString(),"yyyy-MM-dd");
			 fmtCommissionRate = map.get("fmtCommissionRate").toString();
			 fmtCommissionFee = map.get("fmtCommissionFee").toString();
			 fmtAuctionPrice = map.get("fmtAuctionPrice").toString();
			 fmtTbFinishTotalPrice = map.get("fmtTbFinishTotalPrice").toString();
 
			String sql = "INSERT IGNORE  INTO `db-mayn-erp-prd`.`shop_union_fee` ( "
					+ "`SUF_DATE`,"
					+ "`SUF_SHOP_ID`,"
					+ "`SUF_CAMPAIGN_ID`, "
					+ "`SUF_CAMPAIGN_NAME`, "
					+ "`SUF_COMMISSION_RATE`,"
					+ " `SUF_TB_TRADE_PARENT_ID`, "
					+ "`SUF_TB_TRADEID`, "
					+ "`SUF_TB_AUCTION_TITLE`,"
					+ " `SUF_EARNING_TIME`,"
					+ " `SUF_TK_COMMISSION_FEE`, "
					+ "`SUF_NICK_NAME`, "
					+ "`SUF_TK_COMMISSION_RATE`,"
					+ " `SUF_TB_AUCTION_PRICE`,"
					+ " `SUF_TB_AUCTION_NUM`, "
					+ "`SUF_TK_PUB_ID`, "
					+ "`SUF_TB_FINISH_TOTAL_PRICE`, "
					+ "`SUF_TB_TRADE_CREATE_TIME`,"
					+ " `SUF_TB_TRADE_FINISH_TIME`, "
					+ "`SUF_FMT_COMMISSION_RATE`, "
					+ "`SUF_FMT_COMMISSION_FEE`, "
					+ "`SUF_FMT_AUCTION_PRICE`, "
					+"`SUF_FMT_TB_FINISH_TOTAL_PRICE`,"
					+"`SUF_CREATE_DATETIME`,"
					+"`SUF_CREATE_BY`,"
					+"`SUF_MODIFY_DATETIME`,"
					+"`SUF_MODIFY_BY`,"
					+ "`SUF_DEL`)"
					
					+ " VALUES  ('" +  sufDate
					+"','" + shopId
					+"','" + campaignId
					+"','" + campaignName
					+ "','"+ commissionRate
					+ "','"+ tbTradeParentId
					+ "','"+ tbTradeId
					+ "','"+ tbAuctionTitle
					+ "','"+ earningTime
					+ "','"+ tkCommissionFee
					+ "','"+ nickname
					+ "','"+ tkCommissionRate
					+ "','"+ tbAuctionPrice
					+ "','"+ tbAuctionNum
					+ "','"+ tkPubId
					+ "','"+ tbFinishTotalPrice
					+ "','"+ tbTradeCreateTime
					+ "','"+ tbTradeFinishTime
					+ "','"+ fmtCommissionRate
					+ "','"+ fmtCommissionFee
					+ "','"+ fmtAuctionPrice
					+ "','"+ fmtTbFinishTotalPrice
					+ "','"+ sufCreateDatetime
					+ "','"+ sufCreateBy
					+ "','"+ sufModifyDatetime
					+ "','"+ sufModifyBy
					+ "','"+ sufDel
					+ "');";
			
			 //LOG.info("保存数据的tbTradeId--->:"+tbTradeId);
//			 LOG.info("保存数据的时间--->"+sufDate);
			 //LOG.info("数据的时间:earningTime--->"+earningTime);
			 ret = Db.use("erp").update(sql);
			 
			if(   ret > 0){
				LOG.info("update-->插入成功！");
				return true;
			}else if(Db.use("erp").update(sql) == 0){
				LOG.info("update-->数据已存在");
				return true;
			}else {
				LOG.info("插入失败！");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			String mailText = "淘宝客数据插入失败"+"\r\n"+Thread.currentThread().getStackTrace()[1].getMethodName() + " Exception,Msg=" + e.getMessage();
		    SendCloudMailUtil.sendMailCode(mailText,"service@mayn.com.cn");			
		}

		return false;
	
	}
	
}
